﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using myComics.Tools;
using System.Windows.Threading;

namespace myComics.BO
{
    public class Comic : INotifyPropertyChanged
    {
        private BitmapImage _currentStrip;
        private PageCrawler _pageCrawler;
        public string Name { get; set; }

        public BitmapImage CurrentStrip
        {
            get
            {
                return _currentStrip;                
            }
        }

        public string CurrentUrl
        {
            get
            {
                return _pageCrawler.CurrentUrl;
            }
        }

        public Comic(string virualFolder)
        {
            _pageCrawler = new PageCrawler() { VirtualFolder = virualFolder };
            _pageCrawler.GetCurrentComicUrlAsyncCompleted += new PageCrawler.GetCurrentComicUrlAsyncCompletedHandler(_pageCrawler_GetCurrentComicUrlAsyncCompleted);
            _pageCrawler.GoToPreviousStripAsyncCompleted += new PageCrawler.GoToPreviousStripAsyncCompletedHandler(_pageCrawler_GoToPreviousStripAsyncCompleted);
            _pageCrawler.GoToNextStripStripAsyncCompleted += new PageCrawler.GoToNextStripStripAsyncCompletedHandler(_pageCrawler_GoToNextStripStripAsyncCompleted);            
        }

        public void Refresh()
        {
            _pageCrawler.GetCurrentComicUrlAsync();
        }

        void _pageCrawler_GoToNextStripStripAsyncCompleted()
        {
            _pageCrawler.GetCurrentComicUrlAsync();
        }

        void _pageCrawler_GoToPreviousStripAsyncCompleted()
        {
            _pageCrawler.GetCurrentComicUrlAsync();
        }

        void _pageCrawler_GetCurrentComicUrlAsyncCompleted(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                _currentStrip = new BitmapImage(new Uri(url));                
            }
            RaisePropertyChanged("CurrentStrip");
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public void Next()
        {
            _pageCrawler.GoToNextStripStripAsync();
        }

        public void Previous()
        {
            _pageCrawler.GoToPreviousStripAsync();
        }       

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}
